package com.mylib.libcore.mediaplayer;

import android.media.MediaPlayer;
import android.net.wifi.WifiManager;

import com.mylib.libcore.utils.UIUtils;

import java.io.IOException;

/**
 * @author Administrator
 * @date 2020/1/29-15:35
 * @description 自定义ManagedMediaPlayer继承MediaPlayer，拓展MediaPlayer的功能，控制播放状态
 **/
public class ManagedMediaPlayer extends MediaPlayer implements MediaPlayer.OnCompletionListener {



    public enum Status {
        IDLE, INITIALIZED, STARTED, PAUSED, STOPPED, COMPLETED
    }

    private Status mState;

    private OnCompletionListener mOnCompletionListener;

    public ManagedMediaPlayer() {
        super();
        mState = Status.IDLE;
        super.setOnCompletionListener(this);
    }

    @Override
    public void reset() {
        super.reset();
        mState = Status.IDLE;
    }

    @Override
    public void setDataSource(String path) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
        super.setDataSource(path);
        mState = Status.INITIALIZED;
    }

    @Override
    public void start() {
        super.start();
        mState = Status.STARTED;
    }

    @Override
    public void setOnCompletionListener(OnCompletionListener listener) {
        this.mOnCompletionListener = listener;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mState = Status.COMPLETED;
        if (mOnCompletionListener != null) {
            mOnCompletionListener.onCompletion(mp);
        }
    }

    @Override
    public void stop() throws IllegalStateException {
        super.stop();
        mState = Status.STOPPED;
    }

    @Override
    public void pause() throws IllegalStateException {
        super.pause();
        mState = Status.PAUSED;
    }

    @Override
    public int getDuration() {
        return super.getDuration();
    }

    public void setState(Status mState) {
        this.mState = mState;
    }

    public Status getState() {
        return mState;
    }

    public boolean isComplete() {
        return mState == Status.COMPLETED;
    }

    public void closeWifi(WifiManager.WifiLock wifiLock){
        // 关闭wifi锁
        if(!UIUtils.isEmpty(wifiLock)){
            if (wifiLock.isHeld()) {
                wifiLock.release();
            }
        }
    }

}
